/*
 * @lc app=leetcode.cn id=814 lang=golang
 *
 * [814] 二叉树剪枝
 */
package Solutions

// @lc code=start
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pruneTree(root *TreeNode) *TreeNode {
	t := &TreeNode{
		Left: root,
		Val:  0,
	}
	var hasOne func(node *TreeNode) bool
	hasOne = func(node *TreeNode) bool {
		if node == nil {
			return false
		}
		left := hasOne(node.Left)
		right := hasOne(node.Right)
		if !left {
			node.Left = nil
		}
		if !right {
			node.Right = nil
		}
		return left || right || node.Val == 1
	}
	hasOne(t)
	return t.Left
}

// @lc code=end
